package com.example.demo.Controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.Controller.SQLController;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.util.*;

@RestController
public class UserController {
    @PostMapping("/getUser")//url: 'http://localhost:8080/getUser'
    public JSONObject getUser(@RequestBody Map<String, String> requestBody){
        String wxid=requestBody.get("wxid");
        SQLController sqlController=new SQLController();
        JSONObject json = new JSONObject();
        Connection connection=sqlController.ConnectToSql("jdbc:mysql://localhost:3306/jidazhidemai","root","gFL123456"+"");
        if(connection!=null){
            try {

                String sql = " select * from User where wxid=?;";
                PreparedStatement preparedStatement = null;
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, wxid);
                ResultSet resultSet = preparedStatement.executeQuery();

                while (resultSet.next()){
                    json.put("status","COMPLETE");
                    json.put("wxid",resultSet.getString("wxid"));
                    json.put("userid",resultSet.getInt("userid"));
                    json.put("username",resultSet.getString("username"));
                    json.put("desc",resultSet.getString("desc"));
                    json.put("gender",resultSet.getInt("gender"));
                    json.put("campus",resultSet.getInt("campus"));
                    json.put("birthday",resultSet.getString("birthday"));
                }

                connection.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return json;
    }
    @PostMapping("/openid")
    public JSONObject getOpenID(@RequestBody Map<String,String> requestBody){
        JSONObject jsonObject=new JSONObject();
        Connection connection=new SQLController().ConnectToSql("jdbc:mysql://localhost:3306/jidazhidemai","root","gFL123456"+"");
        if(connection!=null){
            try{
                String wxcode=requestBody.get("wxcode");
                System.out.println(wxcode);
                String url="https://api.weixin.qq.com/sns/jscode2session?"
                        +"appid=wxbbd9f06542d698c7"
                        +"&secret=506e627741e3319512e1bcd426c001fb"
                        +"&js_code="+wxcode
                        +"&grant_type=authorization_code";//wx2fa6bc32af5836d8,wxbbd9f06542d698c7
                //ad8b2e2f2eb1cd51ff658060be3ccd5e,506e627741e3319512e1bcd426c001fb
                BufferedReader in=null;
                try {
                    URL weChatUrl = new URL(url);
                    // 打开和URL之间的连接
                    URLConnection urlConnection = weChatUrl.openConnection();
                    // 设置通用的请求属性
                    urlConnection.setConnectTimeout(5000);
                    urlConnection.setReadTimeout(5000);
                    // 建立实际的连接
                    urlConnection.connect();
                    // 定义 BufferedReader输入流来读取URL的响应
                    in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuffer sb = new StringBuffer();
                    String line;
                    while ((line = in.readLine()) != null) {
                        sb.append(line);
                    }
                    jsonObject.put("status","COMPLETE");
                    jsonObject.put("wxid",sb.toString());
                    System.out.println(sb.toString());
                    connection.close();
                    return jsonObject;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return  jsonObject;
    }


    @PostMapping("/IDgetUser")
    public JSONObject IDgetUser(@RequestBody JSONObject requestBody){
        String userid= (String) requestBody.get("userid");
        SQLController sqlController=new SQLController();
        JSONObject json = new JSONObject();
        Connection connection=sqlController.ConnectToSql("jdbc:mysql://localhost:3306/jidazhidemai","root","gFL123456"+"");
        if(connection!=null){
            try {

                Statement statement=connection.createStatement();
                ResultSet resultSet=statement.executeQuery("select * from User where userid="+userid);

                while (resultSet.next()){
                    json.put("status","COMPLETE");
                    json.put("wxid",resultSet.getString("wxid"));
                    json.put("userid",resultSet.getInt("userid"));
                    json.put("username",resultSet.getString("username"));
                    json.put("desc",resultSet.getString("desc"));
                    json.put("gender",resultSet.getInt("gender"));
                    json.put("campus",resultSet.getInt("campus"));
                    json.put("birthday",resultSet.getString("birthday"));
                }

                connection.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return json;
    }
    @PostMapping("/updateUser")//url: 'http://localhost:8080/user/update'
    public JSONObject updateUser(@RequestBody JSONObject frontJson){
        System.out.println(frontJson);
        SQLController sqlController=new SQLController();
        JSONObject json = new JSONObject();
        String type=frontJson.getString("type");
        String userid=wxidgetuserid(frontJson.getString("wxid"));
        Connection connection=sqlController.ConnectToSql("jdbc:mysql://localhost:3306/jidazhidemai","root","gFL123456"+"");
        if(connection!=null){
            try {
                if(type.equals("nickname")){
                    String sql="update user set `username`=?  where userid=?;";
                    PreparedStatement pst = connection.prepareStatement(sql);
                    pst.setString(1,frontJson.getString("changedData"));
                    pst.setString(2, userid);
                    pst.executeUpdate();
                } else if (type.equals("desc")) {
                    String sql="update user set `desc`=?  where userid=?;";
                    PreparedStatement pst = connection.prepareStatement(sql);
                    pst.setString(1,frontJson.getString("changedData"));
                    pst.setString(2, userid);
                    pst.executeUpdate();
                } else if (type.equals("gender")) {
                    String sql="update user set `gender`=?  where userid=?;";
                    PreparedStatement pst = connection.prepareStatement(sql);
                    pst.setInt(1, Integer.parseInt(frontJson.getString("changedData")));
                    pst.setString(2, userid);
                    pst.executeUpdate();
                }
                else if (type.equals("campus")) {
                    String sql="update user set `campus`=?  where userid=?;";
                    PreparedStatement pst = connection.prepareStatement(sql);
                    pst.setInt(1, Integer.parseInt(frontJson.getString("changedData")));
                    pst.setString(2, userid);
                    pst.executeUpdate();
                }
                else if (type.equals("birthday")) {
                    String sql="update user set `birthday`=?  where userid=?;";
                    PreparedStatement pst = connection.prepareStatement(sql);
                    pst.setString(1,frontJson.getString("changedData"));
                    pst.setString(2, userid);
                    pst.executeUpdate();
                }
                connection.close();
                json.put("status","COMPLETE");
                json.put("wxid",frontJson.getString("wxid"));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return json;
    }

    public JSONObject createUser(@RequestBody JSONObject frontJson){
        SQLController sqlController=new SQLController();
        JSONObject json = new JSONObject();
        Connection connection=sqlController.ConnectToSql("jdbc:mysql://localhost:3306/jidazhidemai","root","gFL123456"+"");
        if(connection!=null){
            String wxid=frontJson.getString("wxid");
            String username=frontJson.getString("username");
            String sql="";
            json.put("status","COMPLETE");
            json.put("wxid",wxid);
//            json.put("userid",userid);
        }
        return json;
    }

    @PostMapping("/createFav")//url: 'http://localhost:8080/user/createFav'
    public JSONObject createFav(@RequestBody JSONObject frontJson){
        JSONObject json=new JSONObject();
        SQLController sqlController=new SQLController();
        Connection connection=sqlController.ConnectToSql("jdbc:mysql://localhost:3306/jidazhidemai","root","gFL123456"+"");
        if(connection!=null){
            String wxid=frontJson.getString("wxid");
            Integer postid=frontJson.getInteger("postid");

            try {
                String sql1="select fav from `user` where wxid=?";
                PreparedStatement stmt1 = connection.prepareStatement(sql1);
                stmt1.setString(1, wxid);
                ResultSet rs1= stmt1.executeQuery();
                String userOldFavs=null;
                String userNewFavs=null;
                List<String> userFavList=new ArrayList<>();
                boolean fav_is=false;
                while (rs1.next()){
                    userOldFavs=rs1.getString("fav");
                    if(userOldFavs==null){
                        userNewFavs=postid+",";
                        fav_is=true;
                    }else {
                        userFavList= new ArrayList<String>(Arrays.asList(userOldFavs.split(",")));
                        if(userFavList.contains(postid.toString())){
                            //取消收藏
                            userFavList=remove13(userFavList, postid.toString());
                            userNewFavs=String.join(",",userFavList)+",";
                            fav_is=false;
                        }else{
                            //添加收藏
                            userNewFavs=userOldFavs+postid+",";
                            fav_is=true;
                        }
                    }

                }
                //更新该用户的fav字段
                String sql2="update `user` set fav=? where wxid=?";
                PreparedStatement stmt2 = connection.prepareStatement(sql2);
                stmt2.setString(1, userNewFavs);
                stmt2.setString(2,wxid);
                stmt2.executeUpdate();
                stmt2.close();
                connection.close();

                json.put("status","COMPLETE");
                json.put("fav",fav_is);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return json;
    }
    public String wxidgetuserid(String wxid){
        Connection con;
        Map<String, Object> data = new HashMap<>();
        try {
            String driver="com.mysql.cj.jdbc.Driver";
            String url="jdbc:mysql://localhost:3306/jidazhidemai";

            // 数据库的用户名与密码，需要根据自己的设置
            String user="root";
            String password="gFL123456";
            Class.forName(driver);
            //注册JDBC驱动程 序
            //建立连接
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("数据库连接成功");
            }

            //Statement stmt = con.createStatement();
//            String sql = "INSERT INTO tab1 (title,author,submission_date) VALUES ('li','xiao','2020-07028')";
            String sql = " select userid from user where wxid=?;";
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, wxid);
            ResultSet rs = preparedStatement.executeQuery();
            String userid="该用户未注册";
            if (rs.next()){
                userid = rs.getString("userid");
            }
            con.close();
            return userid;

        } catch (ClassNotFoundException e) {
            System.out.println("数据库驱动没有安装");

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
        return "false-出错了";
    }
    public static List<String> remove13(List<String> list, String target){
        int size = list.size();
        for(int i = size - 1; i >= 0; i--){
            String item = list.get(i);
            if(target.equals(item)){
                list.remove(item);
            }
        }
        return list;
    }



}
